package mornd;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author: mornd
 * @dateTime: 2023/5/4 - 18:21
 * 模板方法设计模式
 */
@Component
public class MyBeanPostProcessor
        implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor {

    private static final String BEAN_NAME = "animal";

    @Override
    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        if(beanName.equals(BEAN_NAME)) {
            System.out.println("<<<<<<<销毁之前执行，如@PreDestroy");
        }
    }

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if(beanName.equals(BEAN_NAME)) {
            System.out.println("<<<<<<<实例化之前执行，这里返回的不为null就会替换掉原本的bean");
        }
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if(beanName.equals(BEAN_NAME)) {
            System.out.println("<<<<<<<实例化之后执行，这里返回false会跳过依赖注入阶段");
            //return false;
        }
        return true;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if(beanName.equals(BEAN_NAME)) {
            System.out.println("<<<<<<<依赖注入阶段执行,该方法执行完后会处理这些注解，如@Autowired @Resource @Value");
        }
        return pvs;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals(BEAN_NAME)) {
            System.out.println("<<<<<<<初始化之前，这里的返回值会替换掉原本的bean，如@PostConstruct @ConfigurationProperties");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals(BEAN_NAME)) {
            System.out.println("<<<<<<<初始化之后执行，这里返回值会替换原本的bean，比如代理增强");
        }
        return bean;
    }
}
